package com.hdw.task.controller;

import com.hdw.common.util.LocalDateUtil;
import com.hdw.common.vo.LayMsg;
import com.hdw.task.bean.vo.Xxl24hTriggerVO;
import com.hdw.task.core.exception.XxlJobException;
import com.hdw.task.core.model.XxlJobGroup;
import com.hdw.task.core.model.XxlJobInfo;
import com.hdw.task.core.model.XxlJobUser;
import com.hdw.task.core.route.ExecutorRouteStrategyEnum;
import com.hdw.task.core.scheduler.MisfireStrategyEnum;
import com.hdw.task.core.scheduler.ScheduleTypeEnum;
import com.hdw.task.core.thread.JobScheduleHelper;
import com.hdw.task.core.thread.JobTriggerPoolHelper;
import com.hdw.task.core.trigger.TriggerTypeEnum;
import com.hdw.task.core.util.I18nUtil;
import com.hdw.task.mapper.XxlJobGroupMapper;
import com.hdw.task.service.LoginService;
import com.hdw.task.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import com.xxl.job.core.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * index controller
 *
 * @author xuxueli 2015-12-19 16:13:16
 */
@Controller
@RequestMapping("/jobinfo")
@Api(tags = "调度任务管理")
@CrossOrigin(origins = "*", maxAge = 3600)
public class JobInfoController {
    private static Logger logger = LoggerFactory.getLogger(JobInfoController.class);

    @Resource
    private XxlJobGroupMapper xxlJobGroupDao;
    @Resource
    private XxlJobService xxlJobService;

    @RequestMapping
    public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "-1") int jobGroup) {

        // 枚举-字典
        model.addAttribute("ExecutorRouteStrategyEnum", ExecutorRouteStrategyEnum.values());        // 路由策略-列表
        model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());                                // Glue类型-字典
        model.addAttribute("ExecutorBlockStrategyEnum", ExecutorBlockStrategyEnum.values());        // 阻塞处理策略-字典
        model.addAttribute("ScheduleTypeEnum", ScheduleTypeEnum.values());                        // 调度类型
        model.addAttribute("MisfireStrategyEnum", MisfireStrategyEnum.values());                    // 调度过期策略

        // 执行器列表
        List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();

        // filter group
        List<XxlJobGroup> jobGroupList = filterJobGroupByRole(request, jobGroupList_all);
        if (jobGroupList == null || jobGroupList.size() == 0) {
            throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
        }

        model.addAttribute("JobGroupList", jobGroupList);
        model.addAttribute("jobGroup", jobGroup);

        return "jobinfo/jobinfo.index";
    }

    public static List<XxlJobGroup> filterJobGroupByRole(HttpServletRequest request, List<XxlJobGroup> jobGroupList_all) {
        List<XxlJobGroup> jobGroupList = new ArrayList<>();
        if (jobGroupList_all != null && jobGroupList_all.size() > 0) {
            XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
            if (loginUser.getRole() == 1) {
                jobGroupList = jobGroupList_all;
            } else {
                List<String> groupIdStrs = new ArrayList<>();
                if (loginUser.getPermission() != null && loginUser.getPermission().trim().length() > 0) {
                    groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
                }
                for (XxlJobGroup groupItem : jobGroupList_all) {
                    if (groupIdStrs.contains(String.valueOf(groupItem.getId()))) {
                        jobGroupList.add(groupItem);
                    }
                }
            }
        }
        return jobGroupList;
    }

    public static void validPermission(HttpServletRequest request, int jobGroup) {
        XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        if (!loginUser.validPermission(jobGroup)) {
            throw new RuntimeException(I18nUtil.getString("system_permission_limit") + "[username=" + loginUser.getUsername() + "]");
        }
    }

    @GetMapping("/pageList")
    @ResponseBody
    public LayMsg pageList(Integer page, Integer limit) {
        return xxlJobService.pageList((page - 1) * limit, limit, 0, 0, null, null, null);
    }

    @GetMapping("/list")
    @ResponseBody
    public LayMsg pageList() {
        List<XxlJobInfo> list = xxlJobService.list();
        return LayMsg.success().addData(list);
    }

    @PostMapping("/add")
    @ResponseBody
    public ReturnT<String> add(@RequestBody XxlJobInfo jobInfo) {
        jobInfo.setJobGroup(1);
        jobInfo.setGlueType("BEAN");
        jobInfo.setScheduleType("CRON");
        jobInfo.setMisfireStrategy("DO_NOTHING");
        jobInfo.setExecutorFailRetryCount(1);
        jobInfo.setExecutorRouteStrategy("FIRST");
        return xxlJobService.add(jobInfo);
    }

    @PostMapping("/update")
    @ResponseBody
    public ReturnT<String> update(@RequestBody  XxlJobInfo jobInfo) {
        return xxlJobService.update(jobInfo);
    }

    @GetMapping("/remove")
    @ResponseBody
    public ReturnT<String> remove(int id) {
        return xxlJobService.remove(id);
    }

    @GetMapping("/stop")
    @ResponseBody
    public ReturnT<String> pause(int id) {
        return xxlJobService.stop(id);
    }

    @GetMapping("/start")
    @ApiOperation(value = "启动")
    @ResponseBody
    public ReturnT<String> start(int id) {
        return xxlJobService.start(id);
    }

    @RequestMapping("/trigger")
    @ResponseBody
    @ApiOperation(value = "执行一次")
    public ReturnT<String> triggerJob(int id, String executorParam, String addressList) {
        // force cover job param
        if (executorParam == null) {
            executorParam = "";
        }

        JobTriggerPoolHelper.trigger(id, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList);
        return ReturnT.SUCCESS;
    }

    @GetMapping("/nextTriggerTime")
    @ResponseBody
    public ReturnT<List<String>> nextTriggerTime(String scheduleType, String scheduleConf) {
        XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
        paramXxlJobInfo.setScheduleType(scheduleType);
        paramXxlJobInfo.setScheduleConf(scheduleConf);
        List<String> result = new ArrayList<>();
//		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
//
// Date lastTime = sdf.parse("2021-06-18 15:33:15");
            Date lastTime = new Date();
            for (int i = 0; i < 5; i++) {
                lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
                if (lastTime != null) {
                    result.add(DateUtil.formatDateTime(lastTime));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ReturnT<List<String>>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type") + I18nUtil.getString("system_unvalid")) + e.getMessage());
        }
        return new ReturnT<List<String>>(result);

    }
    @PostMapping("/triggerTime24h")
    @ResponseBody
    public LayMsg triggerTime24h(@RequestBody List<Map<String,String>> list) {
        List<Xxl24hTriggerVO> triggerVOList = new ArrayList<>();
        Xxl24hTriggerVO triggerVO;
        XxlJobInfo paramXxlJobInfo = new XxlJobInfo();
        Date now = new Date(),lastTime,nextDayBegin = LocalDateUtil.nextDayBegin(now);
        int count;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        boolean fgExec = false;
        TreeMap<Long,Xxl24hTriggerVO> dataMap = new TreeMap<>();
        for(Map<String,String> map:list) {
            count = 0;
            lastTime=now;
            fgExec = false;
            paramXxlJobInfo.setScheduleType("CRON");
            paramXxlJobInfo.setScheduleConf(map.get("cron"));
            triggerVO = new Xxl24hTriggerVO();
            try {
                lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
                while(nextDayBegin.after(lastTime)) {
                    fgExec = true;
                    if(count++==0) {
                        triggerVO.setNextTimeDesc(LocalDateUtil.dateDiffString(now,lastTime));
                        triggerVO.setNextTime(lastTime.getTime()-now.getTime());
                    }
                    lastTime = JobScheduleHelper.generateNextValidTime(paramXxlJobInfo, lastTime);
                    if(count>150) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(fgExec) {
                triggerVO.setJobname(map.get("jobDesc"));
                triggerVO.setTimes(count);
                dataMap.put(triggerVO.getNextTime(),triggerVO);
            }

        }
        return LayMsg.success().addData(dataMap);
    }

}
